﻿#pragma once

#include <atomic>
#include <functional>
#include <memory>
#include <string>
#include <functional>
#include "event2/event.h"

enum EVENT_TYPE
{
    CACHE_READ_ERROR,   /* 读错误 */
    CACHR_WRITE_ERROR,  /* 写错误 */
    CACHE_CLOSE_RES,    /* 对端关闭 */
    CACHE_CONNECT,      /* 连接成功 */
    CACHE_CONNECT_ERROR,      /* 连接错误 */
    CACHE_CONNECT_TIMEOUT,  /* 连接超时 */
    CACHE_PROBE,
};

class EventCache
{
public:
    EventCache(int size);
    ~EventCache();

    int init(struct event_base* m_base, int ip, int port);
    int init(struct event_base* m_base, int nsocket);
    
    void shutdown();
    void SetCallBack(
        std::function<void(void*)> readcb, std::function<void(int, void*)> eventcb, void* user_data
    );

    int SendData(const char* buff, int bufflen);
    int ReadData(char* buff, int readlen);

private:

    inline bool IsEmptyCache(std::atomic<int>& start, std::atomic<int>& end) { return start == end; }

    /* 接收缓冲区读写 */
    int RReadCache(char* buff, int buffsize);
    int RWriteCache(int nSocket);

    /* 发送缓冲区读写 */
    int SReadCache(int nSocket);
    int SWriteCache(const char* buff, int buffsize);

    void ConnectEvent(int nSokcet, int events);
    void EventProssess(int nSocket, short events);
    int ConnectServer(int ip, int port);

    int                 m_size;
    int                 m_socket;
    int                 m_status;  /* 0 未初始化状态，1 初始化状态 */

    std::atomic<int>    m_start, m_end;
    std::atomic<int>    m_start_send, m_end_send;

    char*               m_data;                /* 接收缓冲区 */
    char*               m_send_data;           /* 发送缓冲区 */

    struct event* m_general_evwent;
    struct event* m_write_event;

    struct event_base*  m_base;

    void*               m_user_data;
    std::function<void(void*)> m_readcb;
    std::function<void(int, void*)> m_eventcb;
};
typedef std::shared_ptr<EventCache>  EventCachePtr;

